#include<iostream>
#include<unistd.h>
#include<signal.h>
#include<sys/wait.h>
#include<sys/types.h>
using namespace std;
void handler(int signo)
{
    cout<<"child quit,father get a signal:"<<signo<<endl;
}
void CleanupChild(int signo)
{
    // if(signo==SIGCHLD)
    // {
    //     pid_t rid=waitpid(-1,nullptr,0);
    //     if(rid>0)
    //     {
    //         cout<<"wait child process:"<<rid<<endl;
    //     }
    // }
    // cout<<"cleanup child process done"<<endl;

    if(signo==SIGCHLD)
    {
        while(true)
        {
            pid_t rid=waitpid(-1,nullptr,WNOHANG);
            if(rid>0)
            {
                cout<<"wait child process:"<<rid<<endl;
            }
            else
            {
                break;
            }
        }
    }
    cout<<"cleanup child process done"<<endl;
}
int main()
{
    signal(SIGCHLD,CleanupChild);
    for(int i=0;i<100;i++)
    {
        pid_t id=fork();
        if(id==0)
        {
            //child
            int cnt=5;
            while(cnt--)
            {
                sleep(1);
            }
            std::cout<<"child process died,pid:"<<getpid()<<endl;
            exit(0);
        }
    }
    //father
    while(true)
    {
        sleep(1);
        cout<<"parent process:"<<getpid()<<endl;
    }

    return 0;
}